<template>
  <view class="submiteOrder">
    <view class="bgRadius zitiInfo" v-if="addressInfo&&addressInfo.pickup==1&&addressInfo.store_name">
      <view class="bgImg flex">
        <view class="left">
          <image :src="getImgUrl(addressInfo.image)"  mode="scaleToFill" />
        </view>
        <view class="right flex flex-direction flex-bt"  style="width: 100%;">
          <view class="flex flex-bt title">
            <view class="name two-omit" style="max-width: 250rpx;">{{addressInfo.store_name}}</view>
            <view class="km">距我{{getDistance(34.414525,131.525632,addressInfo.latitude,addressInfo.longitude)}}km</view>
          </view>
          <view class="address">
            {{addressInfo.province}}{{addressInfo.city}}{{addressInfo.area}}{{addressInfo.address}}
          </view>
        </view>
      </view>
      <view class="zitiRen flex">
        <view class="flex-1" @click="openPickup">
          <view class="name">提货人</view>
          <view class="value">
            {{pickInfo.pickup_name?pickInfo.pickup_name:'请输入提货人姓名'}}
          </view>
        </view>
        <view class="flex-1" @click="openPickup">
          <view class="name">联系方式</view>
          <view class="value">
            {{pickInfo.pickup_phone?pickInfo.pickup_phone:'请输入提货人手机号'}}
            
          </view>
        </view>
      </view>
    </view>
    <view class="bgRadius" v-if="addressInfo&&addressInfo.pickup==1&&!addressInfo.store_name">
      <noData content="暂无自提点，请联系管理员哦" acImg="/static/nodata/noZiti.png"></noData>  
    </view>
    <view class="bgRadius" style="padding:30rpx 20rpx;" v-if="Object.keys(addressLists).length==0&&addressInfo.pickup==2" @click="menuJump({is_tab: false,link: '/pages/address/jiaAddress',link_type: 1})">
      <view class="noAddress">
        <view class="flex flex-align flex-bt">
          <view class="name flex flex-align">
            <image  src="@/static/shop/shop06.png"  mode="scaleToFill"  />
            <view>暂无地址，请先添加哦～</view>
          </view>
          <view class="value">
            <uni-icons type="right" size="24" color="#323333"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    <view class="bgRadius addressInfo flex flex-bt flex-align" v-if="Object.keys(addressLists).length!=0&&addressInfo.pickup==2" @click="menuJump({is_tab: false,link: '/pages/address/address',link_type: 1})">
      <view class="left">
        <view class="name"><text v-if="addressLists.is_default">默认</text> {{addressLists.name}} {{addressLists.phone}}</view>
        <view class="value">
          {{addressLists.province}}{{addressLists.city}}{{addressLists.area}}{{addressLists.address}}
        </view>
      </view>
      <view class="right">
        <uni-icons type="right" size="24"></uni-icons>
      </view>
    </view>
    <view class="bgRadius shopInfo">
      <view class="homeTitle"><text>共{{dataInfo.number}}件商品</text></view>
      <view class="shopList">
        <view class="shopItem flex flex-bt">
          <view class="left flex">
            <image :src="getImgUrl(dataInfo.goods_cover)"  mode="scaleToFill" />
            <view class="flex flex-direction flex-bt">
              <view class="name">{{dataInfo.goods_name}}</view>
              <view class="text">
                <view>{{dataInfo.goods_spec}}</view>
              </view>
            </view>
          </view>
          <view class="right">
            <view class="price">
             <text v-if="dataInfo.goodTypeData.id==1">￥</text>
             {{dataInfo.price_selling}} 
             <text v-if="dataInfo.goodTypeData.id!=1">{{dataInfo.goodTypeData.name}}</text>
            </view>
            <view class="number">x{{dataInfo.number}}</view>
          </view>
        </view>
      </view>
      <view class="quanBao flex flex-align flex-end" v-if="dataInfo.return_coupon" @click="openZeng">
        <view class="right flex flex-align">
          <view class="name">{{ dataInfo.return_coupon[0].name}}*{{ dataInfo.return_coupon[0].num }}...</view>
          <view class="value">
            <uni-icons type="right" size="16" color="#fff"></uni-icons>
          </view> 
        </view>
      </view>
      <view class="list">
        <view class="flex flex-align flex-bt">
          <view class="name">订单备注</view>
          <view class="value flex flex-align flex-end">
            <input :adjust-position="false" type="text" placeholder="请输入" v-model="order_desc">
          </view>
        </view>
        <view class="flex flex-align flex-bt">
          <view class="name">商品总额</view>
          <view class="value">
            <text v-if="dataInfo.goodTypeData.id==1">￥</text>
            {{NP.times(dataInfo.price_selling, dataInfo.number)}}
            <text v-if="dataInfo.goodTypeData.id!=1">{{dataInfo.goodTypeData.name}}</text>
          </view>
        </view>
        <view class="flex flex-align flex-bt" v-if="dataInfo.postage!=0">
          <view class="name">运费</view>
          <view class="value">{{dataInfo.postage==0?'包邮':'￥'+dataInfo.postage}}</view>
        </view>
        <view class="flex flex-align flex-bt" @click="openQuan" v-if="validCoupons&&validCoupons.length!=0&&dataInfo.use_coupon_num!=0">
          <view class="name">优惠券</view>
          <view class="value flex flex-align">
            <view>-¥{{couponDiscount}}</view>
            <uni-icons type="right" size="16" color="#323333"></uni-icons>
          </view>
        </view>
        <!-- <view class="flex flex-align flex-bt" @click="openCoin">
          <view class="name">虚拟币抵扣</view>
          <view class="value flex flex-align">
            <view>-¥{{coinDiscount}}</view>
            <uni-icons type="right" size="16" color="#323333"></uni-icons>
          </view>
        </view> -->
        <!-- <view class="flex flex-align flex-bt">
          <view class="name">总计</view>
            <view class="value red" v-if="dataInfo.goodTypeData.id==1">￥{{totalAmount}}</view>
            <view class="value red" v-if="dataInfo.goodTypeData.id!=1"><text v-if="totalAmount!=0">￥</text><text style="font-size: 30rpx;" v-if="totalAmount!=0">{{totalAmount}}+</text>{{dataInfo.price_selling*dataInfo.number}} 
            <text>{{dataInfo.goodTypeData.name}}</text>
          </view>
        </view> -->
      </view>
    </view>
    <view class="bgRadius zhifuType">
      <view class="homeTitle"><text>支付方式</text></view>
      <view class="list">
        <view class="flex flex-align flex-bt">
          <view class="left flex flex-align">
            <image class="Img" src="@/static/shop/shop04.png" mode="scaleToFill" />
            <view class="value">微信支付</view>
          </view>
          <view class="right">
            <uni-icons type="checkbox-filled" size="28" color="#FE7431"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    <view style="height: 130rpx;"></view>
    <view class="footer flex flex-align flex-bt">
      <view class="flex flex-align left">
        <view class="name">合计:</view>
        <view class="value red" v-if="dataInfo.goodTypeData.id==1"><text>￥</text>{{totalAmount}} 
          <!-- <text>礼品卡</text> -->
        </view>
        <view class="value red" v-if="dataInfo.goodTypeData.id!=1"><text v-if="totalAmount!=0">￥</text><text style="font-size: 36rpx;" v-if="totalAmount!=0">{{totalAmount}}+</text>{{NP.times(dataInfo.price_selling, dataInfo.number)}} 
          <text>{{dataInfo.goodTypeData.name}}</text>
        </view>
      </view>
      <view class="btn flex flex-align" >
        <view class="yjmingxi" v-if="couponDiscount!=0">
          <view class="name" @click="openCoupon">查看明细 <uni-icons type="top" size="16" color="#969799"></uni-icons></view>
          <view class="flex flex-align flex-end">共优惠 <text class="redPrice">¥{{couponDiscount>NP.times(dataInfo.price_selling, dataInfo.number)?NP.times(dataInfo.price_selling, dataInfo.number):couponDiscount}}</text></view>
        </view>
        <button class="submite" @click="submite">{{dataInfo.goodTypeData.id==1?'提交订单':'确认兑换'}}</button>
      </view>
    </view>
    <quanList ref="quanListRef" :coupon="validCoupons" :dataInfo="dataInfo" @submit="getcoupon"></quanList>
    <virtualCoin ref="virtualCoinRef"></virtualCoin>
    <couponMx ref="couponMxRef"></couponMx>
    <setPickup ref="setPickupRef" @submit="setPickupSub"></setPickup> 
    <giftdetail ref="giftdetailRef" v-if="dataInfo.return_coupon" :dataInfo="dataInfo.return_coupon"></giftdetail>
</view> 
</template>

<script setup lang="ts">
import { ref, unref, watch } from 'vue';
import NP from 'number-precision';
import quanList from './components/quanList.vue';
import virtualCoin from './components/virtualCoin.vue';
import noData from '@/components/noData.vue';
import couponMx from '@/components/couponMx.vue';
import setPickup from './components/setPickup.vue';
import { menuJump,getDistance, toast,getImgUrl,trottle } from '@/utils/tools';
import { useAuthStore } from '@/stores/counter'
import { goodStorage } from '@/utils/goodStorage';
import { addressList, couponListAvailable, createOrder, currency, orderPay, userAddress, userWallet } from '@/api/user';
import { onLoad, onShow } from '@dcloudio/uni-app';
import giftdetail from './components/giftdetail.vue';
const emit = defineEmits(['submit', 'update:show'])
const quanListRef = ref<InstanceType<typeof quanList>>()
const virtualCoinRef = ref<InstanceType<typeof virtualCoin>>()
const couponMxRef = ref<InstanceType<typeof couponMx>>()
const store=useAuthStore();
const dataInfo =ref(goodStorage.get('routerInfo'))
const setPickupRef = ref<InstanceType<typeof setPickup>>()
const giftdetailRef = ref<InstanceType<typeof giftdetail>>()
// 定义优惠券和虚拟币抵扣金额
const couponDiscount = ref(0);
const coinDiscount = ref(0);
// 定义商品总金额
const totalAmount = ref(0);
const order_desc = ref('')
const selectedCoupon = ref([]);
const addressInfo = ref<Recordable>({})
const addressLists = ref<Recordable>({})

onLoad(()=>{
  
  calculateTotalAmount();
  if(dataInfo.value.goodTypeData.id==1){
    getCoinInfo()
  }
})
onShow(()=>{
  addressLists.value = {}
  setTimeout(() => {
    getAddressInfo()
  })
})
// 计算商品总金额的函数
const calculateTotalAmount = () => {
  const price = parseFloat(dataInfo.value.price_selling);
  const number = parseInt(dataInfo.value.number);
  const postage = parseFloat(dataInfo.value.postage);
  const subtotal = price * number + postage;
  // const subtotal = price * number;
  if(dataInfo.value.goodTypeData.id==1){
    totalAmount.value = NP.minus(subtotal, couponDiscount.value,coinDiscount.value)
    if(totalAmount.value<0){
      totalAmount.value = 0
    }
  }else{
    totalAmount.value = postage
  }
};

async function openQuan(){
  quanListRef.value?.open()
}
async function openCoin(){
  virtualCoinRef.value?.open()
}
async function openCoupon(){
  couponMxRef.value?.open(selectedCoupon.value)
}
function openZeng(){
  giftdetailRef.value?.open()
}
watch(dataInfo, () => {
  calculateTotalAmount();
});
function getcoupon(e: any){
  console.log(JSON.parse(e))
  couponDiscount.value =0
  selectedCoupon.value = JSON.parse(e);
  selectedCoupon.value.forEach((v: { amount_to_cash: number; }) => {
    couponDiscount.value = couponDiscount.value + v.amount_to_cash;
  });
  calculateTotalAmount();
}
function submite(){
  if(Object.keys(store.getstoreInfo).length==0){
    uni.showToast({
      title: '请联系团长绑定关系',
      icon: 'none'
    })
    return

  }
  let data = {
    goods_id: dataInfo.value.code,
    goods_item_id: dataInfo.value.goods_item_id,
    goods_num: dataInfo.value.number,
    order_desc:order_desc.value,
  }
  let orderInfo = {
    order_id:'',
    currency: [
      {
        currency_id: 1,
        have_id: 1,
        amount: totalAmount.value,
        amount_to_cash: totalAmount.value,
      }
    ],
  }
  if(selectedCoupon.value.length!=0){
    orderInfo.currency.push(...selectedCoupon.value)
  }
  if(dataInfo.value.goodTypeData.id!=1){
    const data = {
      currency_id: dataInfo.value.goodTypeData.id,
      have_id: 0,
      amount: dataInfo.value.price_selling*dataInfo.value.number,
      amount_to_cash: dataInfo.value.price_selling*dataInfo.value.number,
    }
    orderInfo.currency.push(data)
  }
  
  if(addressInfo.value.pickup==2){
    data.address_id = addressLists.value.id
    orderInfo.address_id = addressLists.value.id
    if(Object.keys(addressLists.value).length==0){
      uni.showToast({
        title: '请添加收货地址',
        icon: 'none'
      })
      setTimeout(() => {
        menuJump({is_tab: false,link: '/pages/address/address',link_type: 1})
      }, 1000);
      return
    }
  }
  if(addressInfo.value.pickup==1&&pickInfo.value.pickup_name==''&&pickInfo.value.pickup_phone==''){
    uni.showToast({
      title: '请完善信息',
      icon: 'none'
    })
    setPickupRef.value?.open()
    return
  }
  if(dataInfo.value.goodTypeData.id==1){
    uni.showLoading({
      title: '提交订单中...',
      mask: true
    });
    createOrder(data).then((res:any)=>{
      orderInfo.order_id = res.order_id
      uni.hideLoading()
      orderPay(orderInfo).then((res:any)=>{
        if(res.pay_success==1&&res.pay_data==''){
          uni.showToast({
            title: '支付成功',
            icon: 'none'
          })
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/shop/paySuccess?id='+dataInfo.value.goodTypeData.id,
            })
          }, 1000);
        }else if(res.pay_success==1&&res.pay_data!=''){
          onBridgeReady(JSON.parse(res.pay_data))
        }
      })
    })
  }else{
    getwallet(data,orderInfo)
  }
}
function openPickup (){
  console.log(pickInfo.value)
  if(pickInfo.value.pickup_name==''&&pickInfo.value.pickup_phone==''){
    setPickupRef.value?.open()
  }
}
// 用户下单地址
const pickInfo= ref({
  pickup_name:'',
  pickup_phone:''
})

function getAddressInfo(){
  if(Object.keys(store.getstoreInfo).length!=0){
    addressInfo.value = store.getstoreInfo

    console.log(addressInfo.value)
  }else{
    store.getStoreInfos().then((res:any)=>{
      addressInfo.value = res
    })
  }
  if(addressInfo.value.pickup==1&&store.dataUser.pickup_name==''){
   setPickupRef.value?.open()
  }else if(addressInfo.value.pickup==2){
    addressList().then((res: any) => {
      addressLists.value = res[0]
    })
  }
  pickInfo.value = store.dataUser
}
function setPickupSub(){
  store.getUserInfo().then((res:any)=>{
    pickInfo.value = res
  })
}
// 可用货币
const coinInfo = ref()
const couponList = ref([])
const validCoupons = ref([]);
function getwallet(data: { goods_id: any; goods_item_id: any; goods_num: any; order_desc: string; }, orderInfo: { order_id: string; currency: { currency_id: number; have_id: number; amount: number; amount_to_cash: number; }[]; }){
  userWallet({current_type_id:dataInfo.value.goodTypeData.id}).then((res:any)=>{
    coinInfo.value = res
    console.log(coinInfo.value)
    if(coinInfo.value.balance>=NP.times(dataInfo.value.price_selling, dataInfo.value.number)){
      uni.showLoading({
        title: '提交订单中...',
        mask: true
      });
      createOrder(data).then((res:any)=>{
        orderInfo.order_id = res.order_id
        orderPay(orderInfo).then((res:any)=>{
          uni.hideLoading()
          if(res.pay_success==1&&res.pay_data==''){
            uni.showToast({
              title: '支付成功',
              icon: 'none'
            })
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/shop/paySuccess?id='+dataInfo.value.goodTypeData.id,
              })
            }, 1000);
          }else if(res.pay_success==1&&res.pay_data!=''){
            onBridgeReady(JSON.parse(res.pay_data))
          }
        })
      })
    }else{
      uni.showToast({
        title:dataInfo.value.goodTypeData.name + '余额不足',
        icon: 'none'
      })
    }
  })
}
function getCoinInfo(){
  couponListAvailable({goods_id:dataInfo.value.code}).then((res:any)=>{
    couponList.value = res
    validCoupons.value = couponList.value.filter(coupon => {
      return totalAmount.value >= coupon.usage_amount&&dataInfo.value.max_coupon_deduction>=coupon.cash_amount;
    });
    console.log(validCoupons.value)
  })
}
const onBridgeReady = (payResponse: any) => {
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: payResponse.appId,
      timeStamp: payResponse.timeStamp,
      nonceStr: payResponse.nonceStr,
      package: payResponse.package,
      signType: payResponse.signType,
      paySign: payResponse.paySign,
    },
    (res: any) => {
      if (res.err_msg === 'get_brand_wcpay_request:ok') {
        // 支付成功
        setTimeout(() => {
            uni.redirectTo({
              url: '/pages/shop/paySuccess?id='+dataInfo.value.goodTypeData.id,
            })
          }, 1000);
      } else {
        // 支付失败
        
      }
    },
  );
};

</script>

<style scoped lang="scss">
.submiteOrder{padding: 20rpx;}
.noAddress{
  .flex{
    .name{font-size: 28rpx;color: #333;font-weight: bold;
      image{width: 60rpx;height: 60rpx;margin-right: 10rpx;}
    }
    
  }
}
.zitiInfo{padding: 0;
  .bgImg{background: url('@/static/shop/shop03.png') no-repeat;background-size: 100%;padding: 20rpx;
    .left{
      image{
        width: 144rpx;margin-right: 20rpx;height: 144rpx;
      }
    }
    .right{
      .title{font-weight: bold;
        .name{font-size: 30rpx;color: #333;}
        .km{font-size: 24rpx;color: #FE7431;padding-top: 5rpx;}
      }
      .address{font-size: 24rpx;color: #969799;}
    }
  }
  .zitiRen{padding: 30rpx 0;
   .flex-1{text-align: center;
     .name{font-size: 24rpx;color: #969799;}
     .value{font-size: 26rpx;color: #323333;margin-top: 6rpx;font-weight: bold;
      input{font-size: 26rpx;font-weight: normal;}
    }
   }
   .flex-1:last-child{
    border-left: 1px solid #ECECEC;
   }
  }
}
.zhifuType{
  .list{
    .flex{
      .left{
        .Img{width: 80rpx;height: 80rpx;}
        .value{font-size: 28rpx;color: #333;font-weight: bold;margin-left: 10rpx;}
      }
    }
  }
}
.addressInfo{padding-top: 30rpx;
  .left{
    .name{font-size: 28rpx;color: #323232;font-weight: bold;
      text{
        background: #FE7431;padding: 6rpx 15rpx;border-radius: 20rpx;color: #fff;font-size: 20rpx;
      }
    }
    .value{font-size: 26rpx;color: #969799;margin-top: 16rpx;}
  }
 .right{
   .uni-icons{color: #969799;}
  }
}
.shopInfo{
  .list{
    .flex{padding: 6rpx 0;
      .name{font-size: 28rpx;color: #969799;}
      .value{font-size: 28rpx;color: #333;font-weight: bold;
        input{border: none;outline: none;font-size: 28rpx;color: #333;text-align: right;width: 500rpx;}
        text{font-size: 24rpx;}
      }
      .red{
        color: #FE4927;
      }
    }
  }
  .quanBao{background:url('@/static/shop/shop05.png');border-radius: 50rpx;color: #fff;padding-left: 20rpx;margin:20rpx 0;
  background-size: 100% 100%;
   .flex{padding: 14rpx 10rpx 14rpx 0;
     .name{font-size: 24rpx;color: #fff;}
     .value{font-size: 24rpx;color: #FE7431;
      
    }
    }
  }
}
.shopList{
  .shopItem{padding: 20rpx 0;
    .left{
      image{width: 170rpx;height: 170rpx;}
      .flex-direction{margin-left: 20rpx;
        .name{font-size: 28rpx;color: #333;width: 330rpx;font-weight: bold;}
        .text{font-size: 24rpx;color: #969799;margin-top: 10rpx;
         view{background: #F5F6F7;border-radius: 40rpx;padding: 4rpx 20rpx;display: inline-block;}
        }
      }
    }
  .right{text-align: right;font-weight: bold;
    .price{font-size: 32rpx;color: #323233;
      text{font-size: 24rpx;}
    }
    .number{font-size: 24rpx;color: #969799;margin-top: 10rpx;}
   }
  }
}
.footer{background: #fff;position: fixed;bottom:0;left:0;width: 100%;padding:20rpx 20rpx 40rpx;z-index: 11;
  box-sizing: border-box;
  .flex{
    .name{font-size: 28rpx;color: #969799;margin-right: 10rpx;}
    .value{font-size: 36rpx;color: #333;
      font-weight: bold;
      text{font-size: 24rpx;}
    }
    .red{color: #FE4927;}
  }
 .btn{
  .yjmingxi{width: 180rpx;text-align: right;padding-right: 20rpx;
   .name{font-size: 24rpx;color: #969799;}
    .flex{margin-top: 6rpx;font-size:22rpx;font-weight: bold;
      .redPrice{font-size: 24rpx;color: #FE4927;} 
    }
  }
   button{background: #FE7431;border-radius: 40rpx;color: #fff;font-size: 24rpx;padding: 10rpx 50rpx;}
  }
}
.homeTitle{margin-top: 0;margin-bottom: 20rpx;}
</style>